// store/permission.js
// import { asyncRoutes, constantRoutes } from "@/router/index";
import { constantRoutes } from "@/router/index";
import * as menuApi from "@/api/sys/menu";

function getItem() {
  const LoAsyncRoutes =
    JSON.parse(localStorage.getItem("permission_routes")) || [];

  return LoAsyncRoutes;
}
import Layout from "@/layout";
var subObliqueLine = str => {
  if (str === undefined) {
    return str;
  }
  return str.replace(/(^\/*)/g, "");
};
var importPath = comUrl => {
  const path = subObliqueLine(comUrl);
  return resolve => require([`@/${path}.vue`], resolve);
};
function formatRoutes(routes, Layout) {
  const formatRoutesArr = [];
  routes.forEach((route, $ind) => {
    const router = {
      meta: {}
    };
    const {
      title,
      path,
      redirect,
      component,
      icon,
      hidden,
      name,
      children,
      meta
    } = route;
    if (component == "Layout") {
      router["component"] = Layout;
    } else {
      router["component"] = importPath(component);
    }
    // if (redirect !== null) {
    //   router['redirect'] = redirect
    // }
    router["meta"]["icon"] = "form";
    router["meta"]["title"] = meta.title;
    router["path"] = path;
    router["name"] = name;
    router["hidden"] = hidden;
    if (children && children instanceof Array && children.length > 0) {
      router["children"] = formatRoutes(children);
    }
    formatRoutesArr.push(router);
  });
  return formatRoutesArr;
}
const permission = {
  state: {
    routers: constantRoutes,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRoutes.concat(routers);
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { roles } = data;
        const accessedRouters = formatRoutes(getItem(), Layout);
        commit("SET_ROUTERS", accessedRouters);
        setTimeout(() => {
          resolve(accessedRouters);
        }, 200);
      });
    },
    formatRoutes({ commit }, data) {
      return new Promise(resolve => {
        var newRouterList = formatRoutes(data, Layout);
        commit("SET_ROUTERS", newRouterList);
        resolve(newRouterList);
      });
    },
    editRouters({ dispatch,commit }, data) {
      return new Promise((resolve, reject) => {
        menuApi.getUserPermissionByToken().then(res => {
          var menuList = res.data.menu;
          var btnList = res.data.auth;
          localStorage.setItem("permission_routes", JSON.stringify(menuList));
          localStorage.setItem("permission_btnList", JSON.stringify(btnList));
          dispatch('formatRoutes',menuList)
          resolve(menuList)
        }).catch(error => {
          reject(error);
        })

      });
    }
  }
};

export default permission;
